package com.zhang.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import com.zhang.pojo.OrderBean;
import com.zhang.pojo.SaleBean;
import com.zhang.pojo.UserBean;
import com.zhang.service.IOrderService;
import com.zhang.util.ChartUtil;
import org.jfree.chart.servlet.ServletUtilities;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.IOException;
import java.time.LocalDate;
import java.util.List;

@RequestMapping("order")
@RestController
public class OrderController {

    @Autowired
    private IOrderService orderService;

    @RequestMapping("add")
    public String add(HttpServletRequest req, @Valid OrderBean orderBean, BindingResult result) throws JsonProcessingException {

        System.out.println("================>"+orderBean);

        if (result.hasErrors()){
            List<FieldError> errorInfo = result.getFieldErrors();
            System.out.println("==============>"+errorInfo);
            //将错误信息转换为json字符串
            ObjectMapper mapper = new ObjectMapper();
            String string = mapper.writeValueAsString(errorInfo);
            return string;
        }
        UserBean user = (UserBean) req.getSession().getAttribute("user");
        orderService.add(orderBean,user.getUserId());
        return "ok";
    }

    @RequestMapping("findByItem")
    public PageInfo<OrderBean> findByItem(int pageNo, String status, LocalDate start, LocalDate end){
//        if (status == "无限")
        return orderService.findByItem(pageNo, status, start, end);
    }

    @RequestMapping("findByUserId")
    public PageInfo<OrderBean> findByUserId(HttpServletRequest req, int pageNo){

        UserBean user = (UserBean) req.getSession().getAttribute("user");
        return orderService.findByUserId(pageNo,user.getUserId());
    }


    @RequestMapping("findById")
    public OrderBean findById(int orderId) {
        return orderService.findById(orderId);
    }

    @RequestMapping("send")
    public String send(int id){
        orderService.send(id);
        return "ok";
    }

    @RequestMapping("findDeBoy")
    public List<OrderBean> findDeBoy(){
        return orderService.findDeBoy();
    }

    @RequestMapping("finish")
    public String finish(int id){
        orderService.finish(id);
        return "ok";
    }

    @RequestMapping("findAll")
    public List<SaleBean> findAll(int year){
        return orderService.findAll(year);
    }

}
